import { ref } from "vue"
import logo from "@src/assets/logo.svg";
import logoPro from "@src/assets/logo2.svg";
import { MsgFromToBackground } from "../utils/MsgFromToBackground";
import { SD_SYSTEM } from "@src/globalData/enum";
import { closeOtherTabs } from "@src/entries/background/utils/common";
import { promisetTimeOut } from "@src/utils/common";

const CHILD_SYSTEM = import.meta.env.VITE_APP_CHILD_SYSTEM

const logoType = import.meta.env.VITE_APP_LOGO
const logoImg = logoType === 'pro' ? logoPro : logo


export const useApp = () => {
  const logoImageUrl = ref<string>(new URL(logoImg, import.meta.url).href)

  const toReq = async () => {
    // createSpotMarketAllReqLoop(getSpotMarketHeaders() as HeadersInit)
  }

  const openChildSystem = () => {
    const userInfo = sessionStorage.getItem('KUANGJIAZU-PXF-COMMON-PORTAL-SESSION-userInfo-')
    console.log('userInfo', userInfo)
    if(!userInfo) return
    const ticket = JSON.parse(userInfo)?.userInfoExtend?.ticket
    if(!ticket) return
    window.open(`${CHILD_SYSTEM}?ticket=${ticket}`, "_blank");
  }

  const afterLogin = async (timeOut:number) => {
    await promisetTimeOut(timeOut)
    if(SD_SYSTEM.MAIN !== window.location.href) return
    window.location.reload()
  }

  const listenHash = (fn:Function, timeOut:number) => {
    let lastHash = window.location.hash;

    setInterval(function() {
      const cHash = window.location.hash
      if(cHash === '#/outNet') lastHash = cHash
      if(cHash === lastHash) return
      console.log('hashChange xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb')

      if(lastHash === '#/outNet' && cHash === '#/dashboard') fn(timeOut)
    }, 600);  // 每 100 毫秒检查一次
  }

  const init = () => {
    listenHash(afterLogin, 3*1000)

    if(SD_SYSTEM.MAIN === window.location.href) {
      new MsgFromToBackground()

      setTimeout(() => {
        openChildSystem()
      }, 8*1000)
    }
  }

  return {
    logoImageUrl,

    toReq,
    init
  }
}